package com.guozinhs.auto.frame.listener;

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

/**
 * @Author: GuoZi
 * @Date: 2022/2/6 9:40
 */
public class NodeSelectedListener implements MouseListener {

    /**
     * 默认的双击时间间隔(ms)
     */
    public static final Long DOUBLE_CLICK_TIME = 500L;

    private long lastClickTime = 0L;
    private boolean isFocus = false;

    private final Long id;
    private final boolean moveDirIfClick;
    private final boolean moveDirIfDoubleClick;
    private final NodeSelectedEventHandler eventHandler;

    public NodeSelectedListener(Long id, boolean moveDirIfClick, boolean moveDirIfDoubleClick, NodeSelectedEventHandler eventHandler) {
        this.id = id;
        this.moveDirIfClick = moveDirIfClick;
        this.moveDirIfDoubleClick = moveDirIfDoubleClick;
        this.eventHandler = eventHandler;
    }

    @Override
    public void mouseClicked(MouseEvent e) {
    }

    @Override
    public void mousePressed(MouseEvent e) {
        this.isFocus = true;
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        if (!this.isFocus) {
            return;
        }
        boolean moveDir = this.moveDirIfClick;
        if (!moveDir && this.moveDirIfDoubleClick) {
            moveDir = this.isDoubleClick();
        }
        this.eventHandler.stateSelected(this.id, moveDir);
    }

    @Override
    public void mouseEntered(MouseEvent e) {
    }

    @Override
    public void mouseExited(MouseEvent e) {
        this.isFocus = false;
    }

    private boolean isDoubleClick() {
        long current = System.currentTimeMillis();
        boolean isDoubleClick = current - lastClickTime <= DOUBLE_CLICK_TIME;
        this.lastClickTime = current;
        return isDoubleClick;
    }

}
